<template>
	<view class="container">
		<!-- 头部导航 -->
		<u-navbar title="个人信息" :title-bold="true" title-color="#000" :border-bottom="false" custom-class="home-bg" :background="{ background: 'transparent' }"></u-navbar>

		<!-- 头像区域 -->
		<view class="avatar-section" @click="chooseAvatar">
			<view class="avatar-container">
				<image v-if="formData.avatar" class="avatar" :src="formData.avatar" mode="aspectFill"></image>
				<view v-else class="avatar-placeholder flex align-center flex-center">
					<u-icon name="photo" color="#ccc" size="60"></u-icon>
				</view>
			</view>
			<text class="change-avatar-text">点击修改头像</text>
		</view>

		<!-- 表单区域 -->
		<view class="form-section">
			<view class="form-item">
				<text class="label">昵称</text>
				<u-input v-model="formData.nickName" placeholder="请输入" placeholder-class="placeholder-style" @input="inputChange('nickName')"></u-input>
			</view>

			<view class="form-item">
				<text class="label">手机号</text>
				<u-input
					v-model="formData.phonenumber"
					placeholder="请输入"
					placeholder-class="placeholder-style"
					type="number"
					@input="inputChange('phonenumber')"
					:disabled="isEditingPhone ? false : true"
				></u-input>
			</view>

			<view class="form-item">
				<text class="label">姓名</text>
				<u-input v-model="formData.fullName" placeholder="请输入" placeholder-class="placeholder-style" @input="inputChange('fullName')"></u-input>
			</view>

			<view class="form-item">
				<text class="label">身份证号</text>
				<u-input
					v-model="formData.idCardNumber"
					placeholder="请输入"
					placeholder-class="placeholder-style"
					@input="inputChange('idCardNumber')"
					:disabled="isEditingIdCard ? false : true"
				></u-input>
			</view>
		</view>

		<view class="form-time flex flex-between align-center">
			<text class="label">注册日期</text>
			<u-input v-model="formData.createTime" placeholder="" disabled></u-input>
		</view>

		<!-- 底部按钮区域 -->
		<view class="button-section">
			<button class="cancel-btn" @click="cancel">取消</button>

			<u-button class="save-btn" @click="save" :loading="saving">保存</u-button>
		</view>
	</view>
</template>

<script>
import user from '@/api/user.js';
import api from '@/api/index.js';
import { idCardValidate } from '@/utils/validate.js';
export default {
	data() {
		return {
			formData: {},
			isEditingPhone: false, // 是否允许编辑手机号
			isEditingIdCard: false, // 是否允许编辑身份证号
			saving: false, // 是否正在保存
			originalData: {}, // 原始数据，用于比较是否有更改
			path: api.getPathApi(),
			pathImg: api.getPath(),
			avatarUrl: ''
		};
	},
	onLoad(e) {
		this.getInfo();
	},
	methods: {
		chooseAvatar() {
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				sourceType: ['album', 'camera'],

				success: async (res) => {
					const tempFilePath = res.tempFilePaths[0];
					this.formData.avatar = tempFilePath;

					let token = uni.getStorageSync('token');
					let config = {
						header: {}
					};
					config.header['Authorization'] = 'Bearer ' + token;
					//头像上传
					uni.uploadFile({
						url: `${this.path}/common/upload`,
						filePath: tempFilePath,
						name: 'file', // 后台接收的字段名
						header: config.header,
						success: (uploadRes) => {
							this.avatarUrl = JSON.parse(uploadRes.data).fileName;
						},
						fail: (err) => {
							console.error('上传失败', err);
						}
					});
				}
			});
		},

		inputChange(field) {
			// 当输入框内容变化时触发
			if (this.originalData[field] !== this.formData[field]) {
				this.checkIfDataChanged();
			}
		},

		checkIfDataChanged() {
			// 检查数据是否有变化
			const hasChanges = Object.keys(this.originalData).some((key) => this.originalData[key] !== this.formData[key]);

			// 可以在这里启用或禁用保存按钮
			// this.isSaveButtonDisabled = !hasChanges;
		},

		cancel() {
			// 恢复原始数据
			this.formData = JSON.parse(JSON.stringify(this.originalData));
			uni.navigateBack();
		},

		save() {
			this.saving = true;

			// 表单验证
			if (!this.validateForm()) {
				this.saving = false;
				return;
			}

			// 显示加载中
			uni.showLoading({
				title: '保存中...'
			});

			user.setInfo({
				avatar: this.avatarUrl,
				fullName: this.formData.fullName,
				nickName: this.formData.nickName,
				idCardNumber: this.formData.idCardNumber
			})
				.then((res) => {
					uni.hideLoading();
					this.saving = false;
					// 保存成功后更新原始数据
					uni.navigateBack();
				})
				.catch((erro) => {
					console.log(erro);
				});
		},

		validateForm() {
			// 验证必填字段
			if (!this.formData.fullName?.trim()) {
				uni.showToast({
					title: '请输入姓名',
					icon: 'none'
				});
				return false;
			}
			if (!this.formData.phonenumber?.trim()) {
				uni.showToast({
					title: '请输入手机号',
					icon: 'none'
				});
				return false;
			}

			if (!/^1\d{10}$/.test(this.formData.phonenumber)) {
				uni.showToast({
					title: '手机号格式不正确',
					icon: 'none'
				});
				return false;
			}

			if (!this.formData.idCardNumber?.trim()) {
				uni.showToast({
					title: '请输入身份证号',
					icon: 'none'
				});
				return false;
			}

			if (!idCardValidate(this.formData.idCardNumber)) {
				uni.showToast({
					title: '身份证号格式不正确',
					icon: 'none'
				});
				return false;
			}

			if (!this.formData.nickName?.trim()) {
				uni.showToast({
					title: '请输入昵称',
					icon: 'none'
				});
				return false;
			}

			return true;
		},
		getInfo() {
			user.getInfo()
				.then((res) => {
					this.formData = res.data;
					this.formData.avatar = this.pathImg + this.formData.avatar;
					this.originalData = JSON.parse(JSON.stringify(this.formData));
					this.isEditingIdCard = this.formData.idCardNumber ? false : true;
				})
				.catch((erro) => {
					console.log(erro);
				});
		}
	}
};
</script>

<style lang="scss" scoped>
.flex {
	display: flex;
}
.align-center {
	align-items: center;
}
.flex-center {
	justify-content: center;
}
.flex-between {
	justify-content: space-between;
}
.flex-column {
	flex-direction: column;
}
.label {
	width: 160rpx;
	font-size: 32rpx;
	color: #333;
}
.form-time {
	margin: 30rpx;
	padding: 10rpx 30rpx;
	background-color: #fff;
	border-radius: 20rpx;
}
page {
	background-color: #f7f7f7;

	.container {
		padding-bottom: 30rpx;

		.avatar-section {
			margin-top: 108rpx;
			padding: 40rpx 30rpx;
			display: flex;
			flex-direction: column;
			align-items: center;

			.avatar-container {
				width: 160rpx;
				height: 160rpx;
				border-radius: 50%;
				overflow: hidden;
				margin-bottom: 30rpx;
				background-color: #f0f0f0;
				display: flex;
				align-items: center;
				justify-content: center;

				.avatar {
					width: 100%;
					height: 100%;
				}

				.avatar-placeholder {
					width: 100%;
					height: 100%;
				}
			}
			.change-avatar-text {
				margin-top: 20rpx;
				font-weight: 550;
				font-size: 32rpx;
				color: #333333;
			}
		}

		.form-section {
			margin: 30rpx;
			background-color: #fff;
			border-radius: 20rpx;

			.form-item {
				padding: 10rpx 30rpx;
				display: flex;
				align-items: center;
			}

			.form-item:last-child {
				border-bottom: none;
			}

			.placeholder-style {
				color: #c0c4cc;
				font-size: 30rpx;
			}
		}

		.button-section {
			margin-top: 200rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			button {
				width: 132rpx;
				height: 56rpx;
				border-radius: 70rpx 70rpx 70rpx 70rpx;
				font-size: 28rpx;
			}

			.cancel-btn {
				background: #eeeeee;
				color: #777;
				line-height: 56rpx;
				margin-right: 50rpx;
			}

			.save-btn {
				background: #f05a39;
				color: #fff;
			}
		}
	}
}
</style>
